package com.wheel.autoconfigure.mybaits;

import com.wheel.core.utils.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.sql.DataSource;
import java.util.Properties;


@Configuration
@ConditionalOnBean({PlatformTransactionManager.class, DataSource.class})
public class TransactionConfigure {

    private static final Logger log = LoggerFactory.getLogger(TransactionConfigure.class);

    public TransactionConfigure() {
        Log.registered(log);
    }

    private static final String BEAN_NAMES = "*ServImpl";

    private static final String TRANSACTION_INTERCEPTOR = "aopTransactionInterceptor";

    @Bean
    public BeanNameAutoProxyCreator transactionAutoProxyCreator() {
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
        beanNameAutoProxyCreator.setProxyTargetClass(true);
        beanNameAutoProxyCreator.setBeanNames(BEAN_NAMES);
        beanNameAutoProxyCreator.setInterceptorNames(TRANSACTION_INTERCEPTOR);
        Log.configured(log, "EnableTransaction with beanNames:{}", BEAN_NAMES);
        return beanNameAutoProxyCreator;
    }


    /**
     * <dt>Description:transactionInterceptor</dt>
     * <dd>配置事务拦截规则
     * <p>
     * 覆盖已有配置
     * <p>
     * PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Exception
     * <p>
     * 事务类型，传递规则，减号表示该异常回滚，加号表示该异常提交
     * </dd>
     * <dd>author: wnfbx@163.com</dd>
     * <dd>version:1.0 <i>2021/2/4 15:45</i></dd>
     *
     * @param ptm
     * @return org.springframework.transaction.interceptor.TransactionInterceptor
     * @since jdk1.7+
     */
    @Bean(name = TRANSACTION_INTERCEPTOR)
    public TransactionInterceptor transactionInterceptor(PlatformTransactionManager ptm) {
        Properties txProps = new Properties();
        txProps.setProperty("add*", "PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Throwable");
        txProps.setProperty("mdf*", "PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Throwable");
        txProps.setProperty("rmv*", "PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Throwable");
        txProps.setProperty("qry*", "readOnly");
        txProps.setProperty("get*", "readOnly");
        txProps.setProperty("*", "readOnly");
        Log.configured(log, "transactionInterceptor setting:{}", txProps);
        return new TransactionInterceptor(ptm, txProps);
    }

}